/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.common.filters;

import com.pingan.haofang.searchcloud.common.constants.WebConstants;
import com.pingan.haofang.searchcloud.common.context.Visitor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * mock session
 * <p/>
 * Mock时请启动传入如下参数
 * <pre>-DmockUser.userId=1</pre>
 *
 * @author zhangbi617
 * @date 08/05/2017
 */
@Component
@ConditionalOnProperty("mockUser.userId")
public class MockSessionFilter extends OncePerRequestFilter {

    @Value("${mockUser.userId}")
    private Long userId = 1L;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        Visitor visitor = new Visitor();
        visitor.setUserName("测试用户_" + userId);
        visitor.setUserId(userId);
        visitor.setRole(1);
        request.getSession().setAttribute(WebConstants.SESSION_VISITOR_ATTRIBUTE, visitor);

        filterChain.doFilter(request, response);
    }
}
